package department

import (
	"errors"
	"cgs-server/server"
	"cgs-server/server/base"
	"cgs-server/server/model"
	"go.mongodb.org/mongo-driver/bson"
)

type DepartmentRepository interface {
	base.Repository
}

func NewDepartmentRepository() DepartmentRepository {
	return &departMentRepository{
		RepositoryStruct: base.RepositoryStruct{
			CollectionName: server.DepartmentCollectionName,
		},
	}
}

type departMentRepository struct {
	base.RepositoryStruct
}

func (d *departMentRepository) Insert(mdl *model.DataUserModel) error {
	if dept, ok := mdl.Data.(*model.Department); ok {
		if err := d.CheckDB(); err != nil {
			return err
		}
		dept.ResolveEntity(dept, mdl.User)
		_, err := d.Mongo.InsertOne(d.CollectionName, dept)
		return err
	} else {
		return errors.New("Dept type error")
	}
}

func (d *departMentRepository) Update(mdl *model.DataUserModel) error {
	if dept, ok := mdl.Data.(*model.Department); ok {
		if err := d.CheckDB(); err != nil {
			return err
		}
		filter := bson.M{
			"ID": dept.ID,
		}
		dept.ResolveFilter(dept, mdl.User, &filter)
		updateOpt := bson.M{
			"ParentID": dept.ParentID,
			"Ancestors": dept.Ancestors,
			"Name": dept.Name,
			"AdminID": dept.AdminID,
		}
		dept.ResolveUpdateCondition(dept, mdl.User, &updateOpt)
		update := bson.M{
			"$set": updateOpt,
		}
		_, err := d.Mongo.UpdateOne(d.CollectionName, filter, update)
		return err
	} else {
		return errors.New("Dept type error")
	}
}

func (d *departMentRepository) Delete(mdl *model.DataUserModel) error {
	if dept, ok := mdl.Data.(*model.Department); ok {
		if err := d.CheckDB(); err != nil {
			return err
		}
		filter := bson.M{
			"ID": dept.ID,
		}
		_, err := d.Mongo.DeleteOne(d.CollectionName, filter)
		return err
	} else {
		return errors.New("Dept type error")
	}
}

func (d *departMentRepository) Find(mdl *model.DataUserModel) (interface{}, error) {
	if dept, ok := mdl.Data.(*model.Department); ok {
		if err := d.CheckDB(); err != nil {
			return nil, err
		}
		filter := bson.M{}
		dept.ResolveFilter(dept, mdl.User, &filter)
		var results []*model.Department
		err := d.Mongo.FindMany(d.CollectionName, filter, &results)
		return results, err
	} else {
		return nil, errors.New("Dept type error")
	}
}
